package com.oguzhan.blog.scheduloor;

import java.util.Date;
import java.util.TimerTask;

public final class Job extends TimerTask {
 
	private Job nextJob;
	private JobTimer nextJobTimer;
	
	private Runnable executionCtx;
	private Date created;
	private Date scheduled;
	private String name;
	private volatile JobStatus status;
	
	public Job(Runnable executionCtx, Date scheduled, String name) {
		this.created = new Date(); // NOW
		this.status = JobStatus.READY;
		this.scheduled = scheduled;
		this.executionCtx = executionCtx;
		this.name = name;
		this.nextJob = null;
	}
	
	public Job(Runnable executionCtx, Date scheduled) {
		this(executionCtx, scheduled, executionCtx.toString());
	}
	
	void setNextJob(Job job) {
		this.nextJob = job;
	}

	public Runnable getExecutionCtx() {
		return executionCtx;
	}

	public Date getCreated() {
		return created;
	}

	public Date getScheduled() {
		return scheduled;
	}

	public JobStatus getStatus() {
		return status;
	}

	public String getName() {
		return name;
	}
	
	@Override
	public void run() {
		this.status = JobStatus.RUNNING;
		this.executionCtx.run();
		this.status = JobStatus.COMPLETED; 
		
		if (this.nextJob != null) {
			this.nextJobTimer = new JobTimer();
			this.nextJobTimer.schedule(this.nextJob);
		}
	}
	
	@Override
	public boolean cancel() {
		this.status = JobStatus.CANCELLED;
		if (this.nextJobTimer != null) {
			this.nextJobTimer.cancel();
		}
		
		return super.cancel();
	}
	
	@Override
	public boolean equals(Object obj) {
		if (obj instanceof Job) {
			Job o = (Job) obj;
			if (o.getScheduled().equals(this.scheduled) && 
					o.getExecutionCtx().equals(this.executionCtx)) {
				return true;
			}
		}
		
		return false;
	}

	@Override
	public String toString() {
		return "Job [executionCtx=" + executionCtx + ", created=" + created
				+ ", scheduled=" + scheduled + ", name=" + name + ", status="
				+ status + "]\n";
	}

	void schedule() {
		this.status = status;
	}

}
